/**
 * @!ngdoc module
 * @name email.services
 * @description
 *   邮件中心模块服务
 */

angular.module('email.services', [])

/**
 * @ngdoc service
 * @name email.services.EmailUtils
 * @description
 *   邮件中心工具函数集
 */
.factory('EmailUtils', function($state, $ionicPopup, $ionicHistory) {

  return {
    /**
     * @ngdoc     method
     * @name      email.services.EmailUtils#showSendedPopup
     * @methodOf  email.services.EmailUtils
     * @param     {Object}   $scope         angular scope 对象
     * 
     * @description 
     *   显示邮件发送成功后的弹窗提醒
     * @returns   {Object}
     */
    showSendedPopup: function($scope) {
      return $ionicPopup.show({
        title: '邮件发送成功',
        scope: $scope,
        buttons: [
          {
            text: '返回主页',
            onTap: function(){
              $ionicHistory.nextViewOptions({
                disableBack: true
              });
              $state.go('email.index');
            }
          },
          {
            text: '再写一封',
            type: 'button-positive',
            onTap: function(e) {
              $state.reload();
            }
          },
        ]
      });
    },

    /**
     * @ngdoc     method
     * @name      email.services.Email#concatToids
     * @methodOf  email.services.Email
     * @param     {String}   uid      用户 id
     * @description 
     *   合并多个 uid 字符串，并去除相同的 uid
     *   
     * @returns   {String}   合并后的 uid 字符串
     */
    concatToids: function(){
      var argu = arguments;
      var ret = [];

      angular.forEach(arguments, function(argu) {
        var arr = angular.isArray(argu) ?
          argu :
          angular.isString(argu) && argu ?
          argu.split(',') :
          [];

        if(!arr.length) {
          return true;
        }

        angular.forEach(arr, function(a) {
          if(ret.indexOf(a) == -1) {
            ret.push(a);
          }
        })
      });

      return ret.length ? ret.join(',') : '';
    },

    /**
     * @ngdoc     method
     * @name      email.services.Email#goBackOrHome
     * @methodOf  email.services.Email
     * @description 
     *   如果有后退页，则后退，没有则回邮件中心首页
     *   
     * @returns   {Undefined}
     */
    goBackOrHome: function() {
      if($ionicHistory.backView()) {
        $ionicHistory.goBack();
      } else {
        $state.go('email.index');
      }
    }
  };
})

/**
 * @ngdoc service
 * @name email.services.Email
 * @description
 *   邮件中心通用服务
 */
.factory('Email', function($rootScope, $http, $state, $ionicLoading, IbPopup, Settings) {
  var getModuleUrl = function () {
    return Settings.rootUrl + '/mail';
  }
  /**
   * @ngdoc     method
   * @name      email.services.Email#create
   * @methodOf  email.services.Email
   * @param     {Object}   data           邮件数据
   * @description 
   *    新建邮件
   *   
   * @returns   {Object}  $q.defer.promise
   */
  function create(data) {
    return $http.post(getModuleUrl() + '/edit', data)
    .success(function(res) {
      $rootScope.$broadcast('email.create', res);
    })
    .error(Settings.requestError)
  }

  /**
   * @ngdoc     method
   * @name      email.services.Email#remove
   * @methodOf  email.services.Email
   * @param     {String}   emailid           邮件id
   * @description 
   *   删除邮件，移动邮件至回收站
   *   
   * @returns   {Object}  $q.defer.promise
   */
  function remove(emailid) {
    $ionicLoading.show();

    return $http.post(getModuleUrl() + '/del', {
      emailid: emailid
    })
    .success(function(res) {
      if(res.isSuccess) {
        $rootScope.$broadcast('email.remove', emailid);
      } else {
        IbPopup.alert({ template: res.errorMsg });
      }
    })
    .error(Settings.requestError)
    .success($ionicLoading.hide)
    .error($ionicLoading.hide)
  }

  /**
   * @ngdoc     method
   * @name      email.services.Email#removeCompletely
   * @methodOf  email.services.Email
   * @param     {String}   emailid           邮件id
   * @description 
   *   彻底删除邮件
   *   
   * @returns   {Object}  $q.defer.promise
   */
  function removeCompletely(emailid) {
    return $http.post(getModuleUrl() + '/delete', {
      emailid: emailid
    })
    .success(function(res) {
      if(res.isSuccess) {
        $rootScope.$broadcast('email.removeTrash', emailid);
      } else {
        IbPopup.alert({ template: res.errorMsg });
      }
    })
    .error(Settings.requestError)
  }

  function removeOutbox(emailid) {
    return $http.post(getModuleUrl() + '/delete', {
      emailid: emailid
    })
    .success(function(res) {
      if(res.isSuccess) {
        $rootScope.$broadcast('email.removeOutbox', emailid);
      } else {
        IbPopup.alert({ template: res.errorMsg });
      }
    })
    .error(Settings.requestError)
  }

  /**
   * @ngdoc     method
   * @name      email.services.Email#removeCompletelyConfirm
   * @methodOf  email.services.Email
   * @param     {Function}   callback           回调函数
   * @description 
   *   显示彻底删除邮件确认弹窗
   *   
   * @returns   {}
   */
  function removeCompletelyConfirm(callback) {
    return IbPopup.confirm({
      title: '确定彻底删除该邮件吗？'
    })
    .then(function(ok) {
      if(ok && angular.isFunction(callback)) {
        callback();
      }
    });
  }

  /**
   * @ngdoc     method
   * @name      email.services.Email#get
   * @methodOf  email.services.Email
   * @param     {String}   emailid           邮件id
   * @description 
   *   获取指定邮件的数据
   *   
   * @returns   {Object}  $q.defer.promise
   */
  function get(emailid) {
    return $http.get(getModuleUrl() + '/show', {
      params: { id: emailid }
    })
    .error(Settings.requestError)
  }

  /**
   * @ngdoc     method
   * @name      email.services.Email#mark
   * @methodOf  email.services.Email
   * @param     {String}   emailid           邮件id
   * @param     {Boolean=} tomark              加星标还是取消星标
   * @description 
   *   星标邮件或取消邮件星标
   *   
   * @returns   {Object}  $q.defer.promise
   */
  function mark(emailid, tomark) {
    return $http.get(getModuleUrl() + '/mark', {
      params: { emailid: emailid, ismark: !!tomark }
    })
    .success(function() {
      $rootScope.$broadcast('email.mark', emailid, !!tomark);
    })
    .error(Settings.requestError)
  }

  /**
   * @ngdoc     method
   * @name      email.services.Email#recovery
   * @methodOf  email.services.Email
   * @param     {String}   emailid           邮件id
   * @description 
   *   还原回收站中的邮件
   *   
   * @returns   {Object}  $q.defer.promise
   */
  function recovery(emailid) {
    return $http.get(getModuleUrl() + '/recovery', {
      params: { emailid: emailid }
    })
    .success(function(res) {
      if(res.isSuccess) {
        $rootScope.$broadcast('email.recovery', emailid);
      }
    })
    .error(Settings.requestError)
  }

  return {
    create: create,
    get: get,
    remove: remove,
    removeCompletely: removeCompletely,
    removeOutbox: removeOutbox,
    removeCompletelyConfirm: removeCompletelyConfirm,
    mark: mark,
    recovery: recovery
  };
})

/**
 * @ngdoc service
 * @name email.services.EmailList
 * @description
 *   邮件中心列表类
 */

.factory('EmailList', function($http, $ionicLoading, Settings) {
  function EmailList(url, options){
    this.url = url;
    this.options = options;

    this.hasMore = true;
    this.mails = [];

    this.params = {};
  }

  angular.extend(EmailList.prototype, {
    getUrl: function() {
      return Settings.rootUrl + this.url
    },
    /**
     * @ngdoc method
     * @name EmailList#fetch
     * @description 
     *   获取文件列表数据
     *   返回数据格式为
     *   {
     *     datas: [
     *       { addtime, author, uid, subject, content, uptime, readstatus... }
     *       ...
     *     ],
     *     lastid: ''
     *   }
     *   addtime: "1409381646"
     *   
     * @param {Obejct} param 查询条件
     *    catid      {String}         分类 id
     *    lastid     {String}         最后查询到的数据的 id
     *    keyword    {String}         搜索关键词
     * @returns {Object} promise
     */
    fetch: function(params, reset, extend) {
      var _this = this;
      if(reset) {
        this.reset();
      }

      if(extend === false) {
        this.params = params;
      } else {
        angular.extend(this.params, params);
      }

      $ionicLoading.show();

      return $http.get(this.getUrl(), {
        params: this.params
      })

      .success(function(res){
        _this.mails = _this.mails.concat(res.data);
        // 判断是否还能加载更多
        _this.hasMore = !!res.lastid;
      })
      .success($ionicLoading.hide)
      .error($ionicLoading.hide)
    },

    get: function(emailid) {
      var ret = null;
      
      angular.forEach(this.mails, function(mail) {
        if(mail.emailid == emailid) {
          ret = mail;
          return false;
        }
      });

      return ret;
    },

    getLastId: function() {
      return this.mails.length ? 
        this.mails[this.mails.length - 1].emailid || '' :
        '';
    },

    view: function(emailid) {
      var mail = this.get(emailid);
      if(mail) {
        mail.isread = '1';
      }
    },

    search: function(keyword) {
      return this.fetch({
        lastid: '',
        search: keyword
      }, true);
    },

    loadMore: function() {
      return this.fetch({
        lastid: this.getLastId()
      });
    },

    hasMails: function() {
      return !!this.mails.length;
    },

    checkNoData: function() {
      return !this.mails.length && !this.hasMore;
    },

    remove: function(id) {
      var _this = this;

      if(!this.mails.length) {
        return;
      }

      angular.forEach(this.mails, function(mail, i) {
        if(mail.emailid == id) {
          _this.mails.splice(i, 1);
          return false;
        }
      });
    },

    reset: function() {
      this.mails = [];
      this.hasMore = true;
      this.params = {};
    },

    refresh: function() {
      return this.fetch({}, true);
    },

    mark: function(emailid, ismark) {
      var mail = this.get(emailid);
      if(mail) {
        mail.ismark = ismark ? '1' : '0';
      }
    }
  });

  return EmailList;
})

/**
 * @ngdoc service
 * @name email.services.EmailInbox
 * @description
 *   收件箱列表数据
 */
.factory('EmailInbox', function($rootScope, Settings, EmailList) {

  var inbox = new EmailList('/mail&type=inbox');

  $rootScope.$on('email.create', function(evt) {
    inbox.reset();
  });

  $rootScope.$on('email.recovery', function() {
    inbox.reset();
  });

  $rootScope.$on('email.remove', function(evt, emailid) {
    inbox.remove(emailid);
  });

  $rootScope.$on('email.mark', function(evt, emailid, ismark) {
    inbox.mark(emailid, ismark);
  });

  return inbox;
})

/**
 * @ngdoc service
 * @name email.services.EmailTodo
 * @description
 *   待办邮件列表数据
 */
.factory('EmailTodo', function($rootScope, Settings, EmailList) {

  var todo = new EmailList('/mail&type=todo');

  $rootScope.$on('email.recovery', function() {
    todo.reset();
  });

  $rootScope.$on('email.remove', function(evt, emailid) {
    todo.remove(emailid);
  });

  $rootScope.$on('email.mark', function(evt, emailid, ismark) {
    todo.mark(emailid, ismark);
  });

  return todo;
})

/**
 * @ngdoc service
 * @name email.services.EmailOutbox
 * @description
 *   发件箱列表数据
 */
.factory('EmailOutbox', function($rootScope, Settings, EmailList) {

  var outbox = new EmailList('/mail&type=send');

  $rootScope.$on('email.create', function(evt) {
    outbox.reset();
  });

  $rootScope.$on('email.removeOutbox', function(evt, emailid) {
    outbox.remove(emailid);
  });

  $rootScope.$on('email.mark', function(evt, emailid, ismark) {
    outbox.mark(emailid, ismark);
  });

  return outbox;
})

/**
 * @ngdoc service
 * @name email.services.EmailTrash
 * @description
 *   回收站数据
 */
.factory('EmailTrash', function($rootScope, Settings, EmailList) {

  var trash = new EmailList('/mail&type=del');

  $rootScope.$on('email.removeTrash', function(evt, emailid) {
    trash.remove(emailid);
  });

  $rootScope.$on('email.recovery', function(evt, emailid) {
    trash.remove(emailid);
  });

  $rootScope.$on('email.mark', function(evt, emailid, ismark) {
    trash.mark(emailid, ismark);
  });

  $rootScope.$on('email.remove', function(){
    trash.reset();
  })

  return trash;
})

